package com.kobe.game_60;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 
 * The n^(th) term of the sequence of triangle numbers is given by, t_(n) =
 * ½n(n+1); so the first ten triangle numbers are:
 * 
 * 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
 * 
 * By converting each letter in a word to a number corresponding to its
 * alphabetical position and adding these values we form a word value. For
 * example, the word value for SKY is 19 + 11 + 25 = 55 = t_(10). If the word
 * value is a triangle number then we shall call the word a triangle word.
 * 
 * Using words.txt (right click and 'Save Link/Target As...'), a 16K text file
 * containing nearly two-thousand common English words, how many are triangle
 * words?
 * 
 * 
 */
public class _42 {

    static List<Integer> triangleNumber = new ArrayList<Integer>();

    
    /*
     * because a word value sum can't bigger than 100 triangle number
     */
    static {
        for (int i = 1; i < 100; i++) {
            triangleNumber.add(getTriangleNumber(i));
        }
    }

    public static int getTriangleNumber(int n) {
        return n * (n + 1) / 2;
    }

    public static boolean isTriangleNumber(int number) {
        for (int temp : triangleNumber) {
            if (temp == number) {
                return true;
            }
        }
        return false;
    }

    public static int getWordValue(String word) {
        int result = 0;
        for (char cha : word.toCharArray()) {
            result += Character.getNumericValue(cha) - 9;
        }
        return result;
    }

    public static void main(String[] args) throws IOException {
        BufferedReader reader = new BufferedReader(new FileReader(
                "source/words.txt"));
        String line = reader.readLine();
        String[] names = line.split(",");
        String name;
        int result = 0;

        for (String tempName : names) {
            name = tempName.substring(1, tempName.length() - 1);
            if (isTriangleNumber(getWordValue(name))){
                result++;
            }
        }

        System.out.println(result);
    }
}
